import React from 'react';
import {Button, Card, DatePicker, Form, Input, InputNumber, message, Popconfirm, Select, Table, Tooltip,} from 'antd';
import moment from 'moment';

import SearchForm from '../../components/AutoForm/SearchForm';
import {baseServerUrl} from '../../utils/Constant';
import {connect} from 'dva';
import {getAuthority} from "../../utils/authority";
import {stringify} from "qs";

const { Option } = Select;
const { TextArea } = Input;

const EditableContext = React.createContext();

@connect(({ entryOrder, customer }) => ({
  requiredCols: entryOrder.requiredCols,
  customlist: customer.selectListData,
  lineOptions: entryOrder.lineOptions,
  carTypeOptions: entryOrder.carTypeOptions,
}))
class EditableCell extends React.Component {


  customChange = value => {
    const { dispatch } = this.props
    dispatch({
      type: 'entryOrder/lineOptions',
      payload: {customerId: value}
    })
    dispatch({
      type: 'entryOrder/carTypeOptions',
      payload: {customerId: value}
    })
  }

  getLineOption= customerName => {
    const{customlist, lineOptions, dispatch} = this.props

    customlist.forEach(customer => {
      if (customer.code === customerName || customer.label === customerName) {
       let customerId = customer.code
        if(!lineOptions.length){
          dispatch({
            type: 'entryOrder/lineOptions',
            payload: {customerId: customerId}
          })
          dispatch({
            type: 'entryOrder/carTypeOptions',
            payload: {customerId: customerId}
          })
        }
      }
    });
  }
  getInput = (dataIndex, record) => {
    const { customlist, lineOptions, carTypeOptions } = this.props;
    switch (dataIndex) {
      case 'busType':
        return (
          <Select style={{ width: 100 }}>
            <Option value="LD">零担</Option>
            <Option value="DC">单程</Option>
            <Option value="WF">往返</Option>
          </Select>
        );
      case 'loadingPlace':
        return <TextArea rows={3} />;
      case 'loadoffPlace':
        return <TextArea rows={3} />;
      case 'customName':
        return (
          <Select
            style={{ width: 140 }}
            showSearch
            onChange={this.customChange}
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {customlist.map(custom => {
              return <Option value={custom.code}>{custom.label}</Option>;
            })}
          </Select>
        );
      case 'line':
        return (
          <Select
            style={{ width: 220 }}
            showSearch
            onFocus={this.getLineOption(record.customName)}
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {lineOptions.map(custom => {
              return <Option value={custom.code}>{custom.label}</Option>;
            })}
          </Select>
        )
      case 'carType':
        return (
          <Select
            style={{ width: 140 }}
            showSearch
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {carTypeOptions.map(custom => {
              return <Option value={custom.code}>{custom.label}</Option>;
            })}
          </Select>
        )
      case 'pickDate':
        return <DatePicker />;
      case 'aogDate':
        return <DatePicker />;
      case 'amount':
        return <InputNumber />;
      case 'volume':
        return <InputNumber />;
      case 'weight':
        return <InputNumber />;
      case 'vprice':
        return <InputNumber />;
      case 'wprice':
        return <InputNumber />;
      case 'pickFee':
        return <InputNumber />;
      case 'arteryFee':
        return <InputNumber />;
      case 'dropoffFee':
        return <InputNumber />;
      case 'workoverFee':
        return <InputNumber />;
      case 'loadupFee':
        return <InputNumber />;
      case 'loadoffFee':
        return <InputNumber />;
      case 'carFee':
        return <InputNumber />;
      case 'fuelFee':
        return <InputNumber />;
      case 'callbackFee':
        return <InputNumber />;
      case 'escortinFee':
        return <InputNumber />;
      case 'tipFee':
        return <InputNumber />;
      case 'shuttleFee':
        return <InputNumber />;
      default:
        return <Input />;
    }
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      requiredCols,
      selectData,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: requiredCols[title],
              initialValue:
                dataIndex === 'pickDate' || dataIndex === 'aogDate'
                  ? record[dataIndex]
                    ? moment(record[dataIndex])
                    : moment()
                  : record[dataIndex],
            })(this.getInput(dataIndex, record, selectData))}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ entryOrder, customer, loading }) => ({
  tableLoading: loading.effects['entryOrder/page'],
  tableData: entryOrder.pageList,
  pagination: entryOrder.pagination,
  columns: entryOrder.columns,
  searchFields: entryOrder.searchFields,
  searchValues: entryOrder.searchValues,
  editId: entryOrder.editId,
  selectionIds: entryOrder.selectionIds,
  selectedRows: entryOrder.selectedRows,
  customerList: customer.selectListData,
  lineOptions: entryOrder.lineOptions,
  carTypeOptions: entryOrder.carTypeOptions,
}))
class EditableTable extends React.Component {
  rowClassName = (record, index) => {
    if (record.status === 'ENTRY') {
      return 'orderParent';
    }
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.handleSearch();
    dispatch({
      type: 'customer/selectList',
    });
  }
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'entryOrder/handleEdit',
      payload: '',
    });
  };

  save(form, orderId, costId) {
    const { dispatch, customerList, carTypeOptions, lineOptions} = this.props;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const { customName, line, carType } = row;
      customerList.forEach(customer => {
        if (customer.code === customName || customer.label === customName) {
          row.customName = customer.label;
          row.customId = customer.code;
        }
      });
      lineOptions.forEach(customer => {
        if (customer.code === line || customer.label === line) {
          row.line = customer.label;
          row.lineId = customer.code;
        }
      });
      carTypeOptions.forEach(customer => {
        if (customer.code === carType || customer.label === carType) {
          row.carType = customer.label;
          row.carTypeId = customer.code;
        }
      });
      row.pickDate = moment(row.pickDate).add(8, 'h');
      row.aogDate = moment(row.aogDate).add(8, 'h');
      dispatch({
        type: 'entryOrder/save',
        payload: { ...row, orderId, costId },
      }).then(() => {
        this.handleSearch();
      });
    });
  }

  handleEdit(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'entryOrder/handleEdit',
      payload: key,
    });
  }

  handleSearchChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'entryOrder/handleSearchChange',
      payload: fields,
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'entryOrder/handleAdd',
    });
  };

  handleSearch = (flag) => {

    const { dispatch, pagination, searchValues } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
    };
    dispatch({
      type: 'entryOrder/page',
      payload: param,
    });
  };

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'entryOrder/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  onSend = () => {
    const { dispatch, selectionIds } = this.props;
    if (!selectionIds.length) {
      return message.error('请选择一行要提交的数据');
    }
    dispatch({
      type: 'entryOrder/send',
      payload: selectionIds,
    }).then(() => {
      this.handleSearch();
    });
  };

  onDel = () => {
    const { dispatch, selectionIds } = this.props;
    if (!selectionIds.length) {
      return message.error('请选择一行要删除的数据');
    }
    dispatch({
      type: 'entryOrder/del',
      payload: selectionIds,
    }).then(() => {
      this.handleSearch();
    });
  };

  handleDownload = () => {
    let searchParam = {};
    searchParam.token = getAuthority();
    window.open(`${baseServerUrl}/tms/report/entryOrderTemplate?${stringify(searchParam)}`);
  };

  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      dispatch,
    } = this.props;
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const optColumns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.orderId,
        }),
      };
    });
    optColumns.push({
      title: '操作',
      width: '120px',
      fixed: 'right',
      render: (text, record) => {
        const editable = editId === record.orderId;
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <Tooltip placement="bottom" title="保存">
                  <Button
                    size="small"
                    onClick={() => this.save(form, record.orderId, record.costId)}
                    icon="save"
                  />
                </Tooltip>
              )}
            </EditableContext.Consumer>
            <Popconfirm
              title="确认取消?"
              cancelText="取消"
              okText="确定"
              onConfirm={() => this.cancel(record.orderId)}
            >
              <Tooltip placement="bottom" title="撤回">
                <Button size="small" icon="rollback" />
              </Tooltip>
            </Popconfirm>
          </span>
        ) : (
          <Tooltip placement="bottom" title="编辑">
            <Button
              disabled={editId !== '' || record.status !== 'ENTRY'}
              size="small"
              icon="edit"
              onClick={() => this.handleEdit(record.orderId)}
            />
          </Tooltip>
        );
      },
    });

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'entryOrder/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'entryOrder/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
      getCheckboxProps: record => ({
        disabled: record.status !== 'ENTRY', // Column configuration not to be checked
      }),
    };

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="输单->操作"
          layout="inline"
          isSend={true}
          isAdd={true}
          isDel={true}
          isReport={true}
          isDownload={true}
          onDownload={this.handleDownload}
          reportUrl={`${baseServerUrl}/tms/tms-order/reportEntry`}
          onFieldsChange={this.handleSearchChange}
          onAdd={this.handleAdd}
          onSubmit={() => {this.handleSearch('btn')}}
          onDel={this.onDel}
          onSend={this.onSend}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <EditableContext.Provider value={this.props.form}>
          <Table
            components={components}
            bordered
            rowKey="orderId"
            loading={tableLoading}
            dataSource={tableData}
            columns={optColumns}
            rowSelection={rowSelection}
            rowClassName={this.rowClassName}
            scroll={{ x: 'max-content' }}
            size="small"
            pagination={pagination}
          />
        </EditableContext.Provider>
      </Card>
    );
  }
}
const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
